<template>
	<view :style="'color:'+shallowColor" class="index-index">
		<uv-back-top :scroll-top="scrollTop"></uv-back-top>
		<view class="content-index">
			<headers @custom-event="customevent"></headers>
			<el-container>
				<el-aside class="hidden-sm-and-down" width="500px">
					<my :heads="false"></my>
				</el-aside>
				<el-main class="infinite-list" v-infinite-scroll="loadMore"
					style="overflow:auto;padding: 15px;height:calc(100vh - 60px);">
					<view class="waterfall_flow" v-if="flowData.list[0]">
						<view :id="`cont_${index + 1}`" class="cont-box "
							:style="{ width: widthCalc, 'margin-left': index === 0 ? 0 : marginCalc }"
							v-for="(numVal, index) in flowData.column" :key="numVal">
							<view class="list-box" v-for="(item, j) in flowData[`column_${index + 1}`]"
								:key="String(item._id)" @mouseenter="flowData.hoverIndex = [index,j]"
								@mouseleave="flowData.hoverIndex = [-1,-1]">
								<uv-image :customStyle="{'width': '100%'}"
									@click="routed('/pages/index/details?id='+item.toid)"
									:class="index==flowData.hoverIndex[0]&&j==flowData.hoverIndex[1]?'img_tip img_tip-acting cursor-pointer':'img_tip cursor-pointer'"
									:src="uv_image(item.flow)" mode="widthFix" @load="imgLoad(item)"
									@error="imgError(item.flow)">
									<template v-slot:loading>
										<view class="skeleton-placeholder"
											style="width:100%;height:200px;background:#f0f0f0;">
										</view>
									</template>
									<template v-slot:error>
										<uv-image :customStyle="{'width': '100%'}" src="/static/ai.svg"></uv-image>
									</template>
								</uv-image>
								<view class="float-button">
									<view v-show="index==flowData.hoverIndex[0]&&j==flowData.hoverIndex[1]"
										style="margin-bottom: 10px;">
										<view style="display: flex;justify-content: flex-start;align-items: center;">
											<view class="same_style"
												@click="routed('/pages/'+item.flow.type+'/index?id='+item.toid)">一键同款
											</view>
										</view>
										<view class="multi-line-omit" v-if="item.flow.name" style="font-size: 16px;font-weight: bold;">
											{{item.flow.name}}
										</view>
										<view class="title_tip multi-line-omit">
											{{ titlePrompt(item.flow) }}
										</view>
										<view class="desc_tip multi-line-omit">
											{{item.flow.des}}
										</view>
									</view>
								</view>
							</view>
							<el-backtop :visibility-height="500"></el-backtop>
						</view>
					</view>
					<el-empty v-else description="收藏为空"></el-empty>
				</el-main>
			</el-container>
		</view>
		<uv-navbar v-if="!screen" :title="'收 藏'" @leftClick="navigateBack" :placeholder="true"></uv-navbar>
		<tabbars :prop-value="'mapping'"></tabbars>
		<uv-toast ref="toast"></uv-toast>
	</view>
</template>

<script>
	// 引入
	import tabbars from '@/components/tabbar/tabbar.vue';
	import config from '@/common/config'
	import headers from '@/components/header/header.vue';
	import my from '@/pages/my/index';
	import {
		getFavoriteList,
		like
	} from '@/common/api.js';
	import {
		uv_image
	} from '@/common/fun.js';
	export default {
		components: {
			// 注册组件
			tabbars,
			headers,
			my
		},
		data() {
			return {
				pageSize: 10,
				page: 1,
				total: 50, //总条数
				status: 'nomore',
				loading: true,
				loadingText: '正在加载...',
				loadmoreText: '加载更多',
				nomoreText: '没有更多了',

				index: -1,
				scrollTop: 0,
				deepColor: '#4D4D4D',
				shallowColor: '#808080',
				lightColor: '#ccc',
				adjustColumn: null,
				dvcurrent: 0,
				more: false,
				flowData: {
					list: [], // 数据值
					column: 1, // 瀑布列数
					columnSpace: 1, // 瀑布列宽间距
					hoverIndex: [-1, -1], // 当前鼠标悬浮的项索引
				},
				aside: true,
				asideW: 200,
				tips: []
			}
		},
		computed: {
			/* 计算列宽 */
			widthCalc() {
				return `${100 / this.flowData.column - this.flowData.columnSpace}%`;
			},
			/* 计算 margin 外边距 */
			marginCalc() {
				const columnWidth = 100 / this.flowData.column - this.flowData.columnSpace;
				return `${(100 - columnWidth.toFixed(5) * this.flowData.column) / (this.flowData.column - 1)}%`;
			},
		},
		mounted() {
			this.adjustColumnCount();
			uni.onWindowResize((res) => {
				this.adjustColumnCount();
			});
			this.getVuex(true);
		},
		created() {
			// this.getVuex(true);
		},
		onPageScroll(e) {
			this.scrollTop = e.scrollTop;
			// #ifdef APP-NVUE
			this.scrollTop = e.detail.scrollTop;
			// #endif
		},
		methods: {
			uv_image,
			async getVuex(ee = false) {
				var that = this;
				const currentPage = ee ? this.page : 0;
				if (!ee) {
					this.$uv.vuex('preloadData', []);
				}
				this.loading = true;
				const res = await getFavoriteList({
					custom: {
						auth: true,
						toast: false,
					},
					params: {
						list: 'true',
						pageSize: this.pageSize,
						page: currentPage,
					}
				});
				if (res) {
					// 处理数据渲染
					if (res.data) {
						let len = 0;
						if (ee) {
							len = this.flowData.list.length;
							this.flowData.list = [...this.flowData.list, ...res.data];
						} else {
							this.flowData.list = res.data;
							// 初始化列数据
							for (let i = 1; i <= this.flowData.column; i++) {
								this.$set(this.flowData, `column_${i}`, []);
							}
						}
						this.$nextTick(() => this.initValue(len));
					}

					// 更新分页参数
					this.page = res.page + 1;
					this.total = res.total;
					this.status = res.page * res.pageSize < res.total ? 'loadmore' : 'nomore';
				}
			},
			loadMore() {
				// console.log('loadMore', !this.loading);
				if (!this.loading) {
					if (this.status == 'loadmore') {
						this.getVuex(true) //请求更多数据列表
					} else {
						if (this.page > 2) {
							this.$refs.toast.show({
								type: 'error',
								title: '默认主题',
								message: "没有更多数据了"
							})
						}

					}
				} else {
					console.log('加载更多-22');
				}

			},
			titlePrompt(e) {
				if (e.content[0].userPrompt && e.content[0].videoUrl) {
					return e.content[0].userPrompt;
				}
				if (e.content[0].revised_prompt && e.content[0].url) {
					return e.content[0].revised_prompt;
				}
				if (e.content[0]?.data && e.content[0].data[0]) {
					return e.content[0].data[0].revised_prompt
				}
				if (e.content[0].prompt) {
					return e.content[0].prompt;
				}
				if (e.content[0]?.musics) {
					return e.content[0].musics[0].prompt;
				}
			},
			customevent(e) {
				this.aside = e;
				if (e) {
					this.asideW = 200;
				} else {
					this.asideW = 0;
				}

				var that = this;
				setTimeout(function() {
					that.refreshWaterfall(that.adjustColumn, that.asideW)
				}, 1000)
			},
			adjustColumnCount() {
				const query = uni.createSelectorQuery().in(this);
				query.select('.header-sticky-top').boundingClientRect(data => {
					if (data) {
						this.adjustColumn = data;
						var sys = ''
						if (this.isPc) { // 针对桌面平台（Windows和Mac）
							sys = 'pc';
						} else { // 针对移动平台（安卓和iOS）
							sys = 'ios';
							this.aside = false;
							this.asideW = 0;
						}
						this.refreshWaterfall(data, this.asideW, sys);
						// console.log(data, sys);
					}
				}).exec();
			},
			refreshWaterfall(data, asideW, e = '') {
				if (!data || (data && !data.width)) return;
				let newColumnCount = Math.floor((data.width - asideW) / 270);
				if (newColumnCount == 1) {
					newColumnCount = 2;
				}
				if (newColumnCount !== this.flowData.column) {
					this.flowData.column = newColumnCount;
					/* 瀑布流-初始化每一列的数据 */
					for (let i = 1; i <= this.flowData.column; i++) {
						this.$set(this.flowData, `column_${i}`, []);
					}
					if (this.flowData.list) {
						this.$nextTick(() => {
							this.initValue(0); // 数据初始化
						});
					}

				}
			},
			/* 获取最小值的对象 */
			getMinObj(a, s) {
				let m = a[0][s];
				let mo = a[0];
				for (let i = a.length - 1; i >= 0; i--) {
					if (a[i][s] < m) m = a[i][s];
				}
				mo = a.filter(i => i[s] === m);
				return mo[0];
			},
			/* 计算每列的高度 */
			getMinColumnHeight() {
				return new Promise(resolve => {
					const heightArr = [];
					for (let i = 1; i <= this.flowData.column; i++) {
						uni.createSelectorQuery()
							.in(this)
							.select(`#cont_${i}`)
							.boundingClientRect(res => {
								heightArr.push({
									column: i,
									height: res.height
								});
							})
							.exec(() => {
								if (this.flowData.column <= heightArr.length) {
									resolve(this.getMinObj(heightArr, "height"));
								}
							});
					}
				});
			},
			/* 初始化瀑布流数据 */
			async initValue(i) {
				if (i >= this.flowData.list.length) {
					this.loading = false;
					return false;
				}
				const minHeightRes = await this.getMinColumnHeight();
				this.flowData[`column_${minHeightRes.column}`] && this.flowData[`column_${minHeightRes.column}`].push({
					...this.flowData.list[i],
					index: i
				});
			},
			/* 图片加载完成 */
			imgLoad(e) {
				const i = e.index;
				this.initValue(i + 1); // 加载下一条数据
			},
			/* 图片加载失败 */
			imgError(e) {
				const i = e.index;
				this.initValue(i + 1); // 加载下一条数据
			},
			clicklist(ite) {
				if (ite.frist) {
					return;
				}
				this.list.map((item, index) => {
					item.checked = item.name === ite.name ? true : false
				})
			},
			routed(url = '') {
				if (!url) {
					return;
				}
				uni.$uv.route({
					url: url,
					// intercept(params, next) {
					// 	console.log(params, next)
					// 	uni.showLoading({
					// 		title: '等待中...'
					// 	})
					// 	// 模拟处理等待
					// 	setTimeout(() => {
					// 		uni.hideLoading();
					// 		next(true);
					// 	}, 1000)
					// }
				})
			}
		}
	}
</script>
<style scoped lang="scss">
	@import 'element-ui/lib/theme-chalk/display.css';

	body {
		overflow: hidden;
		/* 允许垂直滚动 */
		-webkit-overflow-scrolling: touch;
		/* 使用原生滚动，提高性能 */
		position: fixed;
		/* 固定body位置，防止反弹效果 */
		width: 100%;
		/* 确保宽度覆盖全屏 */
	}

	.index-index {
		height: 100%;
		overflow-x: hidden;
	}

	.CAD {
		min-width: 60px;
		display: flex;
		justify-content: center;
		font-size: 14px;
		margin: 0px 0px 10px 10px;
		padding: 4px 10px;
		border-radius: 5px;
	}

	// 瀑布
	.waterfall_flow {
		padding: 0px;

		.cont-box {
			$borderRadius: 12rpx;
			float: left;
			width: 100%;

			.list-box {
				width: 100%;
				margin-bottom: 10px;
				padding: 0px;
				border-radius: $borderRadius;
				// box-shadow: 0rpx 3rpx 6rpx rgba(0, 46, 37, 0.08);
				position: relative;
				overflow: hidden;

				.img_tip {
					width: 100%;
					// margin-bottom: 10px;
					border-radius: $borderRadius;
					transition: transform 0.5s ease-in-out;
				}

				.img_tip-acting {
					transform: scale(1.4);
					/* 鼠标悬停时放大倍数 */
				}

				.float-button {
					width: calc(100% - 20px);
					position: absolute;
					overflow: hidden;
					bottom: 0px;
					padding: 10px;
					margin: 0px;
					color: white;
					border-radius: 5px;
					background-image: linear-gradient(to bottom, rgba(0, 0, 0, 0), rgba(0, 0, 0, 0.4));

					.same_style {
						cursor: pointer;
						border-radius: 10px;
						background-color: #3C9CFF;
						padding: 3px 10px;
						margin-bottom: 10rpx;
					}
				}

				.title_tip {
					text-align: justify;
					font-size: 26rpx;
					margin-bottom: 10rpx;
					font-weight: bolder;
				}

				.tit_tip {
					text-align: justify;
					font-size: 24rpx;
					margin-bottom: 10rpx;
					margin-left: 3px;
					// color: #CED7E1;
				}

				.desc_tip {
					width: 50rpx;
					text-align: justify;
					font-size: 24rpx;
					margin-bottom: 10rpx;
					margin-top: 10rpx;
				}
			}

			.list-box-no {
				margin-bottom: 0rpx;
			}
		}
	}

	.container {
		display: flex;
		justify-content: center;
	}

	.square {
		// background-color: #09bb07;
		height: 0;
		/* 设置高度为0，使其高度由宽度计算得出 */
		padding-bottom: 23%;
		/* 设置padding-bottom为100%，使得高度等于宽度 */
		position: relative;
		/* 为了内部元素的定位 */
	}

	.search_btn {
		padding: 2px 5px;
		border: 1px solid #ccc;
		border-radius: 5px;
		background-color: #F5FAFF;
		margin-right: 10px;
	}

	// 轮播图
	@mixin flex($direction: row) {
		/* #ifndef APP-NVUE */
		display: flex;
		/* #endif */
		flex-direction: $direction;
	}

	.indicator {
		@include flex(row);
		justify-content: center;

		&__dot {
			cursor: pointer;
			height: 6px;
			width: 6px;
			border-radius: 100px;
			background-color: rgba(255, 255, 255, 0.35);
			margin: 0px 5px;
			margin-top: -2px;
			padding: 2px 10px;
			transition: background-color 0.3s;

			&--active {
				background-color: #ffffff;

			}
		}
	}

	::v-deep .el-carousel__indicator--horizontal .el-carousel__button {
		width: 14px;
		height: 14px;
		background: #bfbfbf;
		border: 1px solid #ffffff;
		border-radius: 50%;
		opacity: 0.5;
	}

	::v-deep .el-carousel__indicator--horizontal.is-active .el-carousel__button {
		width: 14px;
		height: 14px;
		background: #ffffff;
		border-radius: 50%;
		opacity: 1;
	}

	::v-deep .el-carousel__indicators {
		// 指示灯位置
		left: unset;
		transform: unset;
		right: 2%;
	}
</style>